<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>TODO List</title>
	</head>
	<body>
		<div id="example"></div>
		<script src="../js/react.development.js"></script>
		<script src="../js/react-dom.development.js"></script>
		<script src="../js/babel.min.js"></script>
		<script src="../js/prop-types.js"></script>
		<script type="text/babel">
			class App extends React.Component {
				constructor(props) {
					super(props);
					this.state = {
						todos: ["吃饭", "睡觉", "打豆豆"],
					};
					this.addToDo = this.addToDo.bind(this);
				}

				addToDo(todo) {
					const { todos } = this.state;
					todos.unshift(todo);
					this.setState({
						todos,
					});
				}
				render() {
					const { todos } = this.state;
					return (
						<div>
							<h1>TODO List</h1>
							<Add count={todos.length} addToDo={this.addToDo} />
							<List todos={todos} />
						</div>
					);
				}
			}
			class Add extends React.Component {
				constructor(props) {
					super(props);
					this.handleClick = this.handleClick.bind(this);
				}

				handleClick() {
					const todo = this.todoInput.value.trim();
					if (!todo) {
						return;
					}
					this.props.addToDo(todo);
					this.todoInput.value = "";
				}
				render() {
					const { count } = this.props;
					return (
						<div>
							<input type="text" ref={(input) => (this.todoInput = input)} />
							<button onClick={this.handleClick}>ADD # {count + 1}</button>
						</div>
					);
				}
			}
			Add.propTypes = {
				count: PropTypes.number.isRequired,
				addToDo: PropTypes.func.isRequired,
			};
			class List extends React.Component {
				render() {
					const { todos } = this.props;
					return (
						<ul>
							{todos.map((todo, index) => (
								<li key={index}>{todo}</li>
							))}
						</ul>
					);
				}
			}
			List.propTypes = {
				todos: PropTypes.array.isRequired,
			};

			ReactDOM.render(<App />, example);
		</script>
	</body>
</html>
